function [a,P] = Agent(P,S,mode, action_selection, isfollowing, policy)

P_color = P{2};
P_num = P{3};

%global variables needed
global num_players_r;
global num_players_b;
global actions;

if (P_color == 'r')
    num_players = num_players_r;
    num_opponents = num_players_b;
else
    num_players = num_players_b;
    num_opponents = num_players_r;
end

memory = LoadMemory(P);
is_running = memory(1);
action = memory(2);
timer = memory(3);

if (is_running) % if there is an action running, check if its termination conditions are met

    if(action >= 2 && action <= (1+num_players)) % action is PassBall

        if(~PlayerInPossession(P,S,mode) || timer == 2) % termination condition
            [a,P] = SelectNewAction(P,S,mode,action_selection, isfollowing, policy);
        else % termination condition was not met; choose same action again
            [a,P] = PassBall(P,S,mode,action-1);
            SaveMemory(P,is_running, action, timer + 1);
        end

    elseif(action == 2 + num_players) % action is GetOpen

        if (timer == 1 || IsClosest(P,S,mode))
            [a,P] = SelectNewAction(P,S,mode,action_selection, isfollowing, policy);
        else
            [a,P] = GetOpen(P,S,mode);
            SaveMemory(P,is_running, action, timer + 1);
        end
    
    elseif(action == 3 + num_players) % action is GoToBall
        
        if(TeamInPossession(P,S,mode) || timer == 10)
            [a,P] = SelectNewAction(P,S,mode,action_selection, isfollowing, policy);
        else
            [a,P] = GoToBall(P,S,mode);
            SaveMemory(P,is_running, action, timer + 1);
        end
        
    elseif(action > 3 + num_players) % action is BlockPass

            k = action -(3+num_players); %number of player to block; i.e. action 13 is BlockPass(13-8) = BlockPass(5)
            
            if(TeamInPossession(P,S,mode) || IsClosest(P,S,mode) || timer == 10)
                [a,P] = SelectNewAction(P,S,mode,action_selection, isfollowing, policy);
            else
                [a,P] = BlockPass(P,S,mode,k);
                SaveMemory(P,is_running, action, timer + 1);
            end
    end
    
else % there is no action currently running for this player
    [a,P] = SelectNewAction(P,S,mode,action_selection, isfollowing, policy);
end

end

function [a,P] = SelectNewAction(P,S,mode,action_selection, isfollowing, policy)

    if(isfollowing == true) % choose new macro action
        [a,P] = action_selection(P,S,mode,policy); % from an existing policy
        
    else
        [a,P] = action_selection(P,S,mode); % using some other function
    end

end